#define move_to_user_mode() \
__asm__ ("movl %%esp,%%eax\n\t" \
	"pushl $0x17\n\t" \  // Segement Selector   0000000000010 1 11   -> index: 2 TDL: 开启  特权级: 3
	"pushl %%eax\n\t" \  // ESP进栈
	"pushfl\n\t" \		 // EFLAGS进栈
	"pushl $0x0f\n\t" \  // Segement Selector   0000000000001 1 11   -> index: 1 TDL: 开启  特权级: 3
	"pushl $1f\n\t" \    // Segement Selector   0000000000001 1 11   -> index: 3 TDL: 开启  特权级: 3
	"iret\n" \           // 中断返回，寄存器信息从栈中弹出，恢复CPU各种状态
	"1:\tmovl $0x17,%%eax\n\t" \
	"movw %%ax,%%ds\n\t" \
	"movw %%ax,%%es\n\t" \
	"movw %%ax,%%fs\n\t" \
	"movw %%ax,%%gs" \
	:::"ax")
/*
intel开发手册 图6-7
按照要求将
SS
ESP
EFLAGS
CS
EIP
寄存器压栈，用于后续的int中断处理
*/


// start interrupt 开启中断
#define sti() __asm__ ("sti"::)
// close interrupt 关闭中断
#define cli() __asm__ ("cli"::)
#define nop() __asm__ ("nop"::)

#define iret() __asm__ ("iret"::)

#define _set_gate(gate_addr,type,dpl,addr) \
__asm__ ("movw %%dx,%%ax\n\t" \
	"movw %0,%%dx\n\t" \
	"movl %%eax,%1\n\t" \
	"movl %%edx,%2" \
	: \
	: "i" ((short) (0x8000+(dpl<<13)+(type<<8))), \
	"o" (*((char *) (gate_addr))), \
	"o" (*(4+(char *) (gate_addr))), \
	"d" ((char *) (addr)),"a" (0x00080000))

#define set_intr_gate(n,addr) \
	_set_gate(&idt[n],14,0,addr)

#define set_trap_gate(n,addr) \
	_set_gate(&idt[n],15,0,addr)

/*
__asm__ (  "movw %dx , %ax            --> 把edx的低位赋值给eax低位，也就是将 ((char *) (addr) 低位)赋值到eax低位，且已经将eax设置为了 0x00080000,那么最终eax的结果应该是 0x00080000 + ((char *) (addr) 低位)
			movw %0 , %dx             --> 把((short) (0x8000+0<<13)+(15<<8)) = 1000 1111 0000 0000 移动到edx中，因此dex的低位被这个值覆盖，最终 edx中的结果应该是 ((char *) (addr)高位) + 0x8F00
			movl %eax, %1             --> 把eax的值赋值给idt[n]的前4字节
			movl %edx, %2"            --> 把edx的值赋值给idt[n]的后4字节
			: : 
			"i" ((short) (0x8000+0<<13)+(15<<8)),"o" (*((char *)(&idt[n]))), "o" (*(4+(char *)(&idt[n]))), "d" ((char *) (addr)),"a" (0x00080000))
)
*/

#define set_system_gate(n,addr) \
	_set_gate(&idt[n],15,3,addr)  // _set_gate(&idt[0x80],15,3,addr)

#define _set_seg_desc(gate_addr,type,dpl,base,limit) {\
	*(gate_addr) = ((base) & 0xff000000) | \
		(((base) & 0x00ff0000)>>16) | \
		((limit) & 0xf0000) | \
		((dpl)<<13) | \
		(0x00408000) | \
		((type)<<8); \
	*((gate_addr)+1) = (((base) & 0x0000ffff)<<16) | \
		((limit) & 0x0ffff); }

#define _set_tssldt_desc(n,addr,type) \
__asm__ ("movw $104,%1\n\t" \
	"movw %%ax,%2\n\t" \
	"rorl $16,%%eax\n\t" \
	"movb %%al,%3\n\t" \
	"movb $" type ",%4\n\t" \
	"movb $0x00,%5\n\t" \
	"movb %%ah,%6\n\t" \
	"rorl $16,%%eax" \
	::"a" (addr), "m" (*(n)), "m" (*(n+2)), "m" (*(n+4)), \
	 "m" (*(n+5)), "m" (*(n+6)), "m" (*(n+7)) \
	)

#define set_tss_desc(n,addr) _set_tssldt_desc(((char *) (n)),addr,"0x89") // 设置tss本地描述符表,"0x89"
#define set_ldt_desc(n,addr) _set_tssldt_desc(((char *) (n)),addr,"0x82") // 设置tss本地描述符表,"0x82"
